package com.yt.sys.common.config;

import com.yt.common.utils.PKUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "config-server")
@Component("ymlConfig")
@Data
public class YmlConfig implements InitializingBean {

    public static final String WORKID_MUST_INTEGER = "workid must integer value 1 to 31";
    private Logger logger = LoggerFactory.getLogger(getClass());

    // 数据中心的workid，每台服务的workid都不能相同，且取值范围1-31
    private String workId;


    public Long getPkId() {
        Long dbSource = 0L;
        Long result = 0L;
        try {
            PKUtils pKUtils = PKUtils.getInstance(StringUtils.isNotBlank(workId) ? Long.parseLong(workId) : 0);
            result = pKUtils.nextId(dbSource);
        } catch (Exception e) {
            logger.error("主键ID生成错误！", e);
        }
        return result;
    }

    /**
     * 根据数据源获取主键ID
     *
     * @param dbSource
     * @return
     */
    public Long getPkId(Long dbSource) {
        Long result = 0L;
        try {
            PKUtils pKUtils = PKUtils.getInstance(StringUtils.isNotBlank(workId) ? Long.parseLong(workId) : 0);
            result = pKUtils.nextId(dbSource);
        } catch (Exception e) {
            logger.error("主键ID生成错误！", e);
        }
        return result;
    }

    public Long getPkId(String phone) {
        Long result = 0L;
        try {
            PKUtils pKUtils = PKUtils.getInstance(StringUtils.isNotBlank(workId) ? Long.parseLong(workId) : 0);
            result = pKUtils.nextId(phone);
        } catch (Exception e) {
            logger.error("主键ID生成错误！", e);
        }
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (null == workId || "".equals(workId.trim())) {
            throw new IllegalArgumentException(WORKID_MUST_INTEGER);
        }
        int workIdInt = Integer.valueOf(workId.trim());
        if (workIdInt < 1 || workIdInt > 31) {
            throw new IllegalArgumentException(WORKID_MUST_INTEGER);
        }
    }

}
